import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { HttpServcie } from "../../../../../service/http.service";
import { Config } from "../../../../../service/config";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { Observable } from "rxjs";
import * as moment from "moment";
import { PlanDetailBean } from "../../plan-detail.bean";
import { CommFuntion } from "../../../../../service/commFunction";
import { Router } from "@angular/router";
import { UserBean } from "../../../../user/user/bean/user.bean";
import {el} from "@angular/platform-browser/testing/src/browser_util";

@Component({
  selector: "plan-detail-publish",
  templateUrl: "plan-detail-publish.html",
  styleUrls: ["plan-detail-publish.scss"]
})
export class PlanDetailPublishPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  @Output("outPut")
  outPut = new EventEmitter();
  @Input()
  inValue: any = [];
  config: any = Config;
  //系统类型
  planDetailBean: PlanDetailBean = new PlanDetailBean();
  roleTypeList = [];
  _useroptions = []; //角色类型
  _cardTypeoption = [];
  partyList = [];
  user: any = {};
  userBean: UserBean = new UserBean();
  total: string;
  list: any = [];
  programList: any = [];
  allChecked = false;
  indeterminate = false;
  userState = Config.USER_STATE;
  partyType: any = '3,4';
  programs: any = [];
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService,
    private commonFun: CommFuntion,
    private router: Router
  ) {
    this.userBean.pageSize = 999;
    this.userBean.currentPage = 1;
    this.userBean.type = "user";
    this.user = JSON.parse(window.localStorage.getItem("user"));
    this.userBean.partyId = JSON.parse(window.localStorage["user"]).partyId;
    this.userBean.partyType = "3,4";
    this.userBean.cardType = "监察A类,监察B类";
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      beCkedPartyName: [null, [Validators.required]],
      bePartyType: [null, [Validators.required]],
      rsponPartyName: [null, [Validators.required]],
      checkReson: [null, [Validators.nullValidator]],
      adjReason: [null, [Validators.nullValidator]],
      adjDate: [null, [Validators.nullValidator]]
    });
  }

  ngOnChanges() {
    for (const key in this.inValue) {
      if (this.inValue.hasOwnProperty(key)) {
        const element = this.inValue[key];
        let key1 = this.commonFun.toUpercase(key);
        this.planDetailBean[key1 + ""] = element;
      }
    }
    if (this.planDetailBean.programName) {
      this.programs = this.planDetailBean.programName.split(",");
    }

    this.query();
    this.queryProgramList();
  }

  submitForm($event) {
    const updateList: Array<Object> = [];
    const rsPonUserIds : Array<Object> = [];
    const rsPonUserUserNames : Array<Object> = [];
    let isTrue = false;
    // let updateData: any = {};
    this.list.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        if (this.planDetailBean.pdType == '5' && element.partyType != '3'){
          isTrue = true;
        }
        if(this.planDetailBean.checkType=='2'){
          rsPonUserIds.push(element.id);
          rsPonUserUserNames.push(element.userName);
        }
        // updateData = Object.assign({}, element);
      }
    });

    if(isTrue){
      this._notification.create("warning", "警告提示", "委托检测,请选择检测单位");
      return;
    }
    // 检查人员可以多个人。。
    // if (this.planDetailBean.checkType=='2' && updateList.length != 1) {
    //   // 异常
    //   this._notification.create(
    //     "error",
    //     "错误提示",
    //     "请选择一位检查人员！"
    //   );
    //   return;
    // }
    if (this.planDetailBean.checkType=='1' && updateList.length != 1) {
      // 异常
      this._notification.create(
        "warning",
        "警告提示",
        "请选择一个检查单位！"
      );
      return;
    }

    // this.planDetailBean.pdType = this.updateData.pdType;
    if (this.planDetailBean.checkType=='2') {
      this.planDetailBean.rsponUserId = rsPonUserIds.join(',');
      this.planDetailBean.rsponUserName = rsPonUserUserNames.join(',');
      this.planDetailBean.rsponPartyType = updateList[0]["partyType"];
      this.planDetailBean.rsponPartyId = updateList[0]["partyId"];
      this.planDetailBean.rsponPartyName = updateList[0]["partyName"];
    }
    if (this.planDetailBean.checkType=='1') {
      this.planDetailBean.rsponPartyId = updateList[0]["id"];
      this.planDetailBean.rsponPartyName = updateList[0]["partyName"];
      this.planDetailBean.rsponUserId = null;
      this.planDetailBean.rsponUserName = null;
    }
    if (this.programs.length < this.programList.length) {
      this.planDetailBean.programName = this.programs.toString();
    }
    this.isSpinning = true;

    let ob = this.httpServcie.publishPlanDetail(this.planDetailBean);
    ob.subscribe(data => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create("success", "成功提示", "下达成功");
        this.outPut.emit($event);
      } else if (data.status == 401) {
        this._notification.create("error", "失败", "请重新登录");
        this.router.navigateByUrl("/login");
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  query() {
    if (this.planDetailBean.checkType=='1') {
      let param = {
        'id': JSON.parse(window.localStorage["user"]).partyId,
        'parentId': JSON.parse(window.localStorage["user"]).partyId,
        'partyType': this.partyType,
        'pageSize': 999,
        'currentPage': 1
      };
      this.httpServcie.queryListParty(param).subscribe(
        data => {
          if (data.status === 200) {
            this.list = data.data.list;
            this.total = data.data.total;
          } else if (data.status === 401) {
            this.router.navigateByUrl("/login");
            return;
          } else {
            // 异常
            this._notification.create("error", "错误提示", data.message);
          }
        },
        error => {
          console.log(JSON.stringify(error));
        }
      );
    } else {
      this.httpServcie.getUserList(this.userBean).subscribe(
        data => {
          if (data.status === 200) {
            this.list = data.data.list;
            this.total = data.data.total;
          } else if (data.status === 401) {
            this.router.navigateByUrl("/login");
            return;
          } else {
            // 异常
            this._notification.create("error", "错误提示", data.message);
          }
        },
        error => {
          console.log(JSON.stringify(error));
        }
      );
    }
  }

  queryProgramList() {
    let param = {partyId: this.planDetailBean.beCkedPartyId,
                 planDictId: this.planDetailBean.planDictId };
    let tempList : any = [];
    this.httpServcie.queryProgramList(param).subscribe(
      data => {
        if (data.status === 200) {
          tempList = data.data.list;
          if(tempList){
            tempList.forEach(element => {
              if(element){
                this.programList.push(element);
              }
            });
          }else{
            this._notification.create("error", "错误提示", "无可选项目");
          }
          // if (parogramName && parogramName.indexOf(',') != -1) {
          //   for (let tmp in parogramName.split(',')) {
          //     this.programList.push(tmp);
          //   }
          // }
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.userBean.pageSize = event;
    this.userBean.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.userBean.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.userBean.currentPage = event;
    this.query();
  }
}
